package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.io.Externalizable;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.io.OutputUtil;
import org.akomantoso.core.visitor.AKVisitable;
import org.akomantoso.core.visitor.AKVisitor;

/**
 * <pre>
 * 	<xsd:element name="workflow">
 * 		<xsd:complexType>
 * 			<xsd:sequence>
 * 				<xsd:element ref="step" minOccurs="1" maxOccurs="unbounded"/>
 * 		</xsd:sequence>
 * 			<xsd:attributeGroup ref="source"/>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * @since http://www.akomantoso.org/1.0
 */
public final class Workflow implements org.akomantoso.core.data.attribute.Source, Externalizable, AKVisitable {

	public static final String ELEMENT = "workflow";

	// Mandatory
	private String _source;

	// Mandatory (min 1).
	private final List<Step> _steps = new ArrayList<Step>(4);

	/**
	 * @see org.akomantoso.core.data.attribute.Source#getSource()
	 */
	@Override
	public String getSource() {
		return _source;
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		OutputUtil.writeSource(out, this);
		for (int i = 0, n = _steps.size(); i < n; i++) {
			_steps.get(i).writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		_source = in.readAttribute(org.akomantoso.core.data.attribute.Source.ATTRIBUTE);
		Step step;
		int eventType = in.readNext();
		while (true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				if (Step.ELEMENT.equals(in.getLocalName())) {
					_steps.add(step = new Step());
					step.readExternal(in);
				}
				break;
			case InputConstants.END_ELEMENT:
				if (ELEMENT.equals(in.getLocalName())) {
					return;
				}
			}
			eventType = in.readNext();
		}
	}

	/**
	 * @see org.akomantoso.core.data.attribute.Source#setSource(java.lang.String)
	 */
	@Override
	public void setSource(String source) {
		_source = source;
	}

	/**
	 * @see org.akomantoso.core.visitor.AKVisitable#accept(org.akomantoso.core.visitor.AKVisitor)
	 */
	@Override
	public void accept(AKVisitor visitor) {
	}

}